package com.ramos.kuaixiao.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.MyView.SelfDialog;
import com.ramos.kuaixiao.entity.Product;
import com.ramos.kuaixiao.entity.SendOrderDetail;
import com.ramos.kuaixiao.entity.WareHouse;
import com.ramos.kuaixiao.ui.LoginActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import jp.wasabeef.glide.transformations.CropSquareTransformation;

import static com.ramos.kuaixiao.App.mContext;

public class Utils {
    public final static int PHOTO_WITH_DATA = 4;
    public final static int PHOTO_WITH_CAMERA = 3;
    public static File[] mCurrentPhotoFile = new File[5];
    public static int mSelect = -1;
    private static Activity mActivity;
    private static String string = "abcdefghijklmnopqrstuvwxyz";

    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    //校验用户
    public static void validateUser(String mIdStr, String mNameStr, String mPwStr, String mPwCfStr, String mPeopleStr, String mPhoneStr, String mAddressStr, String mEmailStr, String mIntroduceStr) {
        if (StringUtil.isEmpty(mIdStr)) {
            ToastUtils.show("请输入账号");
            return;
        }
        if (StringUtil.isEmpty(mNameStr)) {
            ToastUtils.show("请输入名称");
            return;
        }
        if (StringUtil.isEmpty(mPwStr)) {
            ToastUtils.show("请输入密码");
            return;
        }
        if (StringUtil.isEmpty(mPwCfStr)) {
            ToastUtils.show("请确认密码");
            return;
        }
        if (StringUtil.isEmpty(mPeopleStr)) {
            ToastUtils.show("请填入联系人");
            return;
        }
        if (StringUtil.isEmpty(mPhoneStr)) {
            ToastUtils.show("请填入电话");
            return;
        }
        if (StringUtil.isEmpty(mAddressStr)) {
            ToastUtils.show("请填入地址");
            return;
        }
      /*  if (StringUtil.isEmpty(mEmailStr)) {
            ToastUtils.show("请填入联系人");
            return;
        }
        if (StringUtil.isEmpty(mIntroduceStr)) {
            ToastUtils.show("请填入电话");
            return;
        }*/
        if (!(mPwStr.equals(mPwCfStr))) {
            ToastUtils.show("输入密码不一致");
        }
    }

    /**
     * 得到json文件中的内容
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        //获得assets资源管理器
        AssetManager assetManager = context.getAssets();
        //使用IO流读取json文件内容
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName), "utf-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * 解压assets的zip压缩文件到指定目录
     *
     * @throws IOException
     */
    public static void unZip(Context context, String assetName, String outputDirectory, boolean isReWrite) throws IOException {
        // 创建解压目标目录
        File file = new File(outputDirectory);
        // 如果目标目录不存在，则创建
        if (!file.exists()) {
            file.mkdirs();
        }
        File imagefile = new File(outputDirectory + "/downloadimg");
       // Log.d("setImages", "imagefile " +imagefile.getAbsolutePath());
        if (imagefile.exists() && imagefile.listFiles() != null) {
            //Log.d("setImages", "imagefile.exists() && imagefile.listFiles() != null)= " + App.mImages.size());
            setImages(imagefile);
        } else {
            // 打开压缩文件
            InputStream inputStream = context.getAssets().open(assetName);
            ZipInputStream zipInputStream = new ZipInputStream(inputStream);
            // 读取一个进入点
            ZipEntry zipEntry = zipInputStream.getNextEntry();
            // 使用1Mbuffer
            byte[] buffer = new byte[20 * 1024 * 1024];
            // 解压时字节计数
            int count = 0;
            // 如果进入点为空说明已经遍历完所有压缩包中文件和目录
            while (zipEntry != null) {
                // 如果是一个目录
                if (zipEntry.isDirectory()) {
                    file = new File(outputDirectory + File.separator + zipEntry.getName());
                    // 文件需要覆盖或者是文件不存在
                    if (isReWrite || !file.exists()) {
                        file.mkdir();
                    }
                } else {
                    // 如果是文件
                    file = new File(outputDirectory + File.separator + zipEntry.getName());
                    // 文件需要覆盖或者文件不存在，则解压文件
                    if (isReWrite || !file.exists()) {
                        file.createNewFile();
                        FileOutputStream fileOutputStream = new FileOutputStream(file);
                        while ((count = zipInputStream.read(buffer)) > 0) {
                            fileOutputStream.write(buffer, 0, count);
                        }
                        fileOutputStream.close();
                    }
                }
                // 定位到下一个文件入口
                zipEntry = zipInputStream.getNextEntry();
            }
            zipInputStream.close();
        }
        //ToastUtils.showHandle("商品图片加载完成！");
        if (App.mImages.size() == 0) {
            setImages(imagefile);
        }
    }

    private static void setImages(File file) {
        if (file.exists() && file.listFiles() != null) {
            for (File image : file.listFiles()) {
                //Log.d("setImages", image.getName() + " " + image.getAbsolutePath() + "");
                String[] name = image.getName().split("\\.");
                //Log.d("setImages", name[0] + " " + image.getName() + " " + image.getAbsolutePath() + "");
                App.mImages.put(name[0], image.getAbsolutePath());
                //Log.d("setImages", image.getName() + " " + image.getAbsolutePath());
            }
            //Log.d("setImages", "App.mImages " + App.mImages.size());
        }
    }

    /**
     * 递归查找文件
     *
     * @param baseDirName 查找的文件夹路径
     * @param id          需要查找的文件名
     */
    public static String findFiles(String baseDirName, String id, String barcode) {
        if (App.mImages.size() > 0) {
            Set<Map.Entry<String, String>> entrySet = App.mImages.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                String key = entry.getKey();
                String value = entry.getValue();
                //boolean hasId = getValue(key, id);
                //boolean hasBar = getValue(key, barcode);
                boolean hasId = getValue(id,key);
                boolean hasBar = getValue(barcode,key);
                //Log.d("Product", "entry.getKey() " + key + " " + value + " " + id + " " + barcode);
                if (hasId || hasBar) {
                    //Log.d("Product", "showImg:App.mImages.size() > 0 " + key + " " + value + " " + id + " " + barcode);
                    return value;
                }
            }
        } else {
            File baseDir = new File(baseDirName);       // 创建一个File对象
            if (!baseDir.exists() || !baseDir.isDirectory()) {  // 判断目录是否存在
            }
            String tempName = null;
            //判断目录是否存在
            File tempFile;
            File[] files = baseDir.listFiles();
            for (int i = 0; i < files.length; i++) {
                tempFile = files[i];
                if (tempFile.isDirectory()) {
                    findFiles(tempFile.getAbsolutePath(), id, barcode);
                } else if (tempFile.isFile()) {
                    tempName = tempFile.getName();
                    if (tempName.contains(id) || tempName.contains(barcode)) {
                        //Log.d("Product", "showImg:App.mImages.size() == 0 " + tempName + " " + tempFile.getAbsolutePath() + " " + id + " " + barcode);
                        return tempFile.getAbsolutePath();
                    }
                }
            }
        }
        return null;
    }

    private static boolean getValue(String key, String id) {
        if (StringUtil.isEmpty(key) || StringUtil.isEmpty(id)) {
            return false;
        } else {
            if (key.contains(id)) {
                return true;
            }
        }
        return false;
    }

    public static String showImg(String productId, String productBar) {
        return Utils.findFiles(FileUtil.getImagePath(App.mContext) + "/downloadimg", productId, productBar);
    }

    public static JSONArray getJSONArray(List<SendOrderDetail> list) {
        JSONArray jsonArray = new JSONArray();
        if (list == null || list.isEmpty()) {
            return jsonArray;//nerver return null
        }
        try {
            for (SendOrderDetail order : list) {
                if (order.getStoreHouseName() != null) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("productInfoId", order.getProductInfoId());
                    jsonObject.put("productBarCode", order.getProductBarCode());
                    jsonObject.put("storeHouseId", order.getStoreHouseId());
                    jsonObject.put("storeHouseName", order.getStoreHouseName());
                    jsonObject.put("productInfoName", order.getProductInfoName());
                    jsonObject.put("calcParam", order.getCalcParam());
                    jsonObject.put("smallUnitCount", order.getSmallUnitCount());
                    jsonObject.put("largeUnitCount", order.getLargeUnitCount());
                    jsonObject.put("unitSalePrice", order.getUnitSalePrice());
                    jsonObject.put("productSalePrice", order.getProductSalePrice());
                    //jsonObject.put("comment", order.getComment());
                    jsonObject.put("orderSource", 2);
                    int quantity = 0;
                    if(Integer.valueOf(order.getSmallUnitCount()) == 0) {
                        quantity = Integer.valueOf(order.getCalcParam());
                    } else {
                        quantity = 1;
                    }
                    jsonObject.put("last_discount", order.getLast_discount());
                    jsonObject.put("conversionQuantity", quantity);
                    jsonObject.put("ucti", order.getUcti());
                    jsonObject.put("ucte", order.getUcte());
                    jsonObject.put("salePriceT4", order.getSalePriceT4());
                    jsonObject.put("realUcti",order.getRealUcti());
                    jsonObject.put("realUcte", order.getRealUcte());
                    jsonObject.put("tcti",order.getTcti());
                    jsonObject.put("tcte", order.getTcte());
                    jsonObject.put("discountRate",100);
                    jsonObject.put("taxRate", order.getTaxRate());
                    jsonObject.put("taxAmount", order.getTaxAmount());
                    jsonObject.put("initPrice", order.getInitPrice());
                    jsonArray.put(jsonObject);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonArray;
    }

    public static JSONArray getJSONArray(String array) {
        JSONArray jsonArray = new JSONArray();
        try {
            List<SendOrderDetail> list = com.alibaba.fastjson.JSONArray.parseArray(array, SendOrderDetail.class);
            jsonArray = getJSONArray(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonArray;
    }

    public static List<SendOrderDetail> getList(String array) {
        List<SendOrderDetail> list = new ArrayList<>();
        try {
            list.addAll(com.alibaba.fastjson.JSONArray.parseArray(array, SendOrderDetail.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static String getTime() {
        SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        Date time = new Date();
        return localSimpleDateFormat.format(time);
    }

    public static String formatTime(String paramString) {
        SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        try {
            Date mParamString = localSimpleDateFormat.parse(paramString);
            long l = System.currentTimeMillis() - mParamString.getTime();
            int i = (int) (l / 31536000000L);
            int j = (int) (l / 2592000000L);
            int k = (int) (l / 86400000L);
            int m = (int) (l / 3600000L);
            int n = (int) (l / 60000L);
            if (i >= 1) {
                return i + "年前";
            }
            if (j >= 1) {
                return j + "月前";
            }
            if (k >= 1) {
                return k + "天前";
            }
            if (m >= 1) {
                return m + "小时前";
            }
            if (n > 5) {
                paramString = n + "分钟前";
                return paramString;
            }
            return "刚刚";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static File getFile() {
        return mCurrentPhotoFile[mSelect];
    }

    public static void showImgDialog(final Activity activity, final int select) {
        mActivity = activity;
        if (select == 0) {
            mSelect = 0;
            mCurrentPhotoFile[0] = new File(FileUtil.getLogPath(activity) + "0.png");
        } else if (select == 1) {
            mSelect = 1;
            mCurrentPhotoFile[1] = new File(FileUtil.getLogPath(activity) + "1.png");
        } else if (select == 2) {
            mSelect = 2;
            mCurrentPhotoFile[2] = new File(FileUtil.getLogPath(activity) + "2.png");
        } else if (select == 3) {
            mSelect = 3;
            mCurrentPhotoFile[3] = new File(FileUtil.getLogPath(activity) + "3.png");
        }
        AlertDialog.Builder localBuilder = new AlertDialog.Builder(activity).setTitle("选择图片");
        DialogInterface.OnClickListener local3 = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface paramAnonymousDialogInterface, int which) {
                if (which == 0) {
                    showImgPick(0);
                } else {
                    showImgPick(1);
                }
            }
        };
        localBuilder.setItems(new String[]{"拍照", "从相册中选择"}, local3).show();
    }

    private static void showImgPick(int paramInt) {
        if (paramInt == 0) {
            if (Environment.getExternalStorageState().equals("mounted")) {
                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                Uri uri = Uri.fromFile(getFile());
                //为拍摄的图片指定一个存储的路径
                intent2.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                mActivity.startActivityForResult(intent2, PHOTO_WITH_CAMERA);
            }
        } else {
            Intent localIntent = new Intent("android.intent.action.GET_CONTENT");
            localIntent.setType("image/*");
            mActivity.startActivityForResult(localIntent, PHOTO_WITH_DATA);
        }
    }


    public static void showImage(int i) {
        ImageView iv = (ImageView) mActivity.findViewById(i);
        iv.setVisibility(View.VISIBLE);
        loadImage(iv);
    }

    public static void loadImage(ImageView imageView) {
        glideFile(Utils.getFile(), imageView);
    }

    private static int getRandom(int count) {
        return (int) Math.round(Math.random() * (count));
    }


    private static String getRandomString(int length) {
        StringBuilder sb = new StringBuilder();
        int len = string.length();
        for (int i = 0; i < length; i++) {
            sb.append(string.charAt(getRandom(len - 1)));
        }
        return sb.toString();
    }

    public static void requestResult(int requestCode, Intent paramIntent) {
        if (paramIntent == null) {
            return;
        }
        if (requestCode == Utils.PHOTO_WITH_DATA) {
            //Log.d(TAG, "onActivityResult :: requestCode == PHOTO_WITH_DATA");
            ContentResolver resolver = mActivity.getContentResolver();
            // 照片的原始资源地址
            Uri originalUri = paramIntent.getData();
            try {
                Bitmap originalbitmap = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                //Log.d(TAG, "PHOTO_WITH_CAMERA originalbitmap" + originalbitmap.getByteCount());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (requestCode == Utils.PHOTO_WITH_CAMERA) {
            //Log.d(TAG, "onActivityResult :: requestCode == PHOTO_WITH_CAMERA");
            try {
                Bitmap originalbitmap = BitmapFactory.decodeFile(Utils.getFile().getAbsolutePath());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    //校验用户
    public static void validateUser(String mNameStr, String mAgeStr, String mCityStr, String mPassWdStr, String mConfirmPassWdStr) {
        if (StringUtil.isEmpty(mNameStr)) {
            ToastUtils.show("请填入姓名");
            return;
        }
        if (StringUtil.isEmpty(mAgeStr)) {
            ToastUtils.show("请填入年龄");
            return;
        }
        if (StringUtil.isEmpty(mCityStr)) {
            ToastUtils.show("请选择城市");
            return;
        }
        if (StringUtil.isEmpty(mPassWdStr)) {
            ToastUtils.show("请填入密码");
            return;
        }
        if (StringUtil.isEmpty(mConfirmPassWdStr)) {
            ToastUtils.show("请再次填入密码");
            return;
        }
        if (!(mPassWdStr.equals(mConfirmPassWdStr))) {
            ToastUtils.show("输入密码不一致");
        }
    }

    //加载Glide图片
    public static void glideFile(File file, ImageView imageView) {
        Glide.with(mContext)
                .load(file).dontAnimate()
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .skipMemoryCache(true)
                .into(imageView);
    }

    //加载Glide图片
    public static void glideImage(String image_url1, ImageView imageView) {
        Glide.with(mContext).load(image_url1).dontAnimate().bitmapTransform(new CropSquareTransformation(mContext)).diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageView);

    }

    //动态关闭软键盘
    public static void hintKeyboard(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); //得到InputMethodManager的实例
        if (imm.isActive()) {//如果开启
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);//关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
        }
    }

    //显示登录dialog
    public static void showLoginDialog(final Activity activity) {
        final SelfDialog builder = new SelfDialog(activity);
        builder.setMessage("请先登陆");
        builder.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                builder.dismiss();
            }
        });
        builder.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                activity.startActivity(new Intent(activity, LoginActivity.class));
                builder.dismiss();
            }
        });
        builder.show();
    }

    public static void deleteAllFiles(File root) {
        File files[] = root.listFiles();
        if (files != null)
            for (File f : files) {
                if (f.isDirectory()) { // 判断是否为文件夹
                    deleteAllFiles(f);
                    try {
                        f.delete();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    if (f.exists()) { // 判断是否存在
                        deleteAllFiles(f);
                        try {
                            f.delete();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
    }

    //Bitmap对象保存味图片文件
    public static File saveBitmapFile(Bitmap bitmap) {
        File file = new File(FileUtil.getLogPath(mContext) + "video_cover.png");//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * byte(字节)根据长度转成kb(千字节)和mb(兆字节)
     *
     * @param bytes
     * @return
     */
    public static String bytes2kb(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        if (returnValue > 1)
            return (returnValue + "MB");
        BigDecimal kilobyte = new BigDecimal(1024);
        returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        return (returnValue + "KB");
    }

    public static String getLogPath(Context context) {

        StringBuilder sb = new StringBuilder();
        sb.append(getSDPath());
        sb.append(File.separator);
        sb.append(context.getPackageName());
        sb.append(File.separator);
        sb.append("images/");
        File path = new File(sb.toString());
        if (!path.exists()) {
            path.mkdirs();
        }
        return sb.toString();
    }

    private static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        }
        if (null == sdDir) {
            return "";
        } else {
            return sdDir.toString();
        }
    }

    //byte数组到图片
    public static void byte2image(byte[] data, String path) {
        if (data.length < 3 || path.equals("")) return;
        try {
            FileOutputStream imageOutput = new FileOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 通过经纬度获取距离(单位：米)
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static double getDistance(double lat1, double lng1, double lat2,
                                     double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        return s;
    }

    /**
     * 验证手机格式
     */
      /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9

    ------------------------------------------------
    13(老)号段：130、131、132、133、134、135、136、137、138、139
    14(新)号段：145、147
    15(新)号段：150、151、152、153、154、155、156、157、158、159
    17(新)号段：170、171、173、175、176、177、178
    18(3G)号段：180、181、182、183、184、185、186、187、188、189
    */
    public static boolean isMobileNO(String mobiles) {
        String telRegex = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、4、5、7、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        return !TextUtils.isEmpty(mobiles) && mobiles.matches(telRegex);
    }

    public static Set<String> strToSet(String s) {
        if (StringUtil.isEmpty(s)) {
            return null;
        } else {
            com.alibaba.fastjson.JSONArray array = com.alibaba.fastjson.JSONArray.parseArray(s);
            List<String> list = array.toJavaList(String.class);
            Set<String> set = new HashSet<>(list);
            Log.d("strToSet", "set " + set.size());
            return set;
        }
    }

    public static String setToString(Set<String> set) {
        if (set.size() > 0) {
            List<String> list = new ArrayList<>(set);
            com.alibaba.fastjson.JSONArray array = (com.alibaba.fastjson.JSONArray) com.alibaba.fastjson.JSONArray.toJSON(list);
            Log.d("setToString", "array " + array.size());
            return array.toJSONString();
        } else {
            return null;
        }
    }

    /**
     * 根据 路径 得到 file 得到 bitmap
     *
     * @return
     * @throws IOException
     */
    public static Bitmap decodeFile(File f) throws IOException {
        Bitmap b = null;
        int IMAGE_MAX_SIZE = 600;
        if (f == null) {
            return null;
        }
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        FileInputStream fis = new FileInputStream(f);
        BitmapFactory.decodeStream(fis, null, o);
        fis.close();

        int scale = 1;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        fis = new FileInputStream(f);
        b = BitmapFactory.decodeStream(fis, null, o2);
        fis.close();
        return b;
    }

    public static String getText(String str) {
        if (StringUtil.isEmpty(str)) {
            return null;
        }
        if (str.length() <= 6) {
            return str;
        } else {
            return str.substring(str.length() - 6, str.length());
        }
    }

    public static String getDate() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",Locale.CHINA);
        return sdf.format(d);
    }

    public static final long UPLOAD_LOG_INTERVAL = 2 * 60 * 1000L;
    //以固定周期频率执行任务，最大线程数为5个
    private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);

    public static void startUpdateTask() {
        long delay = (long) (Math.random() * 1000 * 60 * 2);
        executeFixedRate(new CheckUploadTask(), delay, UPLOAD_LOG_INTERVAL);
    }

    ;

    public static void startCheckTask() {
        long delay = (long) (Math.random() * 1000 * 60 * 2);
        executeFixedRate(new CheckUploadTask(), delay, UPLOAD_LOG_INTERVAL);
    }

    ;

    private static class CheckUploadTask extends TimerTask {
        public void run() {
            //checkUploadLog();
        }
    }

    /**
     * 以固定周期频率执行任务
     */
    public static void executeFixedRate(Runnable runnable, long delay, long period) {

        if (period == 0) {
            executor.schedule(
                    runnable,
                    delay,
                    TimeUnit.MILLISECONDS);
        } else {
            executor.scheduleAtFixedRate(
                    runnable,
                    delay,
                    period,
                    TimeUnit.MILLISECONDS);
        }
    }

    public static List<WareHouse> getList(List<WareHouse> mWareList, Set<String> wareHouse) {
        List<WareHouse> list = new ArrayList<>(mWareList);
        //Log.d("getList", "list :" + list.size());
        Iterator<WareHouse> iterator = list.iterator();
        while (iterator.hasNext()) {
            WareHouse ware = iterator.next();
            for (String s : wareHouse) {
                if (ware.getName().equals(s)) {
                    //list.remove(ware);
                    iterator.remove();
                }
            }
        }
        return list;
    }

    public static List<Product.WareInfo> getWare(List<Product.WareInfo> wareList, List<WareHouse> wareHouse) {
        List<Product.WareInfo> list = new ArrayList<>();
        Log.d("StoreNumDB", "StoreNumDB:" + list.size());
        for (WareHouse ware : wareHouse) {
            for (Product.WareInfo wareHouse1 : wareList) {
                //Log.d("StoreNumDB", "getWareHouseName:" + wareHouse1.getWareHouseName() + " " + ware.getName());
                if (wareHouse1.getWareHouseId().equals(ware.getId())) {
                    list.add(wareHouse1);
                }
            }
        }
        return list;
    }

    /***
     * 判断是否有外网连接（普通方法不能判断外网的网络是否连接，比如连接上局域网）
     *
     * @return
     */

    public static boolean ping() {
        String result = null;
        try {
            String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网
            Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
            // 读取ping的内容，可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d("------ping-----", "result content : " + stringBuffer.toString());
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Log.d("----result---", "result = " + result);
        }
        return false;

    }

    /**
     * 检查是否存在SDCard
     *
     * @return
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 2 * 获取版本号 3 * @return 当前应用的版本号 4
     */
    public static int getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String version = info.versionName;
            int versioncode = info.versionCode;
            return versioncode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 2 * 获取版本号 3 * @return 当前应用的版本号 4
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String version = info.versionName;
            int versioncode = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 根据byte数组，生成文件
     */
    public static String getAPKFile(byte[] bfile, String filePath, String fileName) {
        String apkUrl = "";
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + "/" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
            apkUrl = filePath + "/" + fileName;
            Log.d("getAPKFile", "getAPKFile:" + apkUrl);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return apkUrl;
    }


    /**
     * 根据byte数组，生成文件
     */
    public static String getZipFile(byte[] bfile, String filePath, String fileName) {
        String zipUrl = "";
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + "/" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
            zipUrl = filePath + "/" + fileName;
            Log.d("getZipFile", "getZipFile:" + zipUrl);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return zipUrl;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static boolean isNotificationEnabled(Context context) {

        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;
        /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void GoToSetting() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", App.mContext.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", App.mContext.getPackageName());
        }
        App.mContext.startActivity(localIntent);
    }

    public static Scanner readCsv(String path) {
        File file = new File(path);
        FileInputStream fileInputStream;
        Scanner in = null;
        try {
            fileInputStream = new FileInputStream(file);
            in = new Scanner(fileInputStream, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return in;
    }

    public static BufferedReader readCsvBuffer(String path) {
        File file = new File(path);
        FileInputStream fileInputStream;
        BufferedReader bufferedreader = null;
        try {
            fileInputStream = new FileInputStream(file);
            bufferedreader = new BufferedReader(new InputStreamReader(fileInputStream));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bufferedreader;
    }

    public static String replaceStr(String s) {
        if(StringUtil.isEmpty(s)){
            return "";
        }
        return s.replace("\"", "");
    }
}
